<template>
    <div class="upload-box">
        <el-upload
            action="#"
            :id="uuid"
            :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
            :multiple="false"
            :drag="props.drag"
            :disabled="self_disabled"
            :show-file-list="false"
            :accept="props.fileType.join(',')"
            :http-request="handleHttpUpload"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError">
            <template v-if="imageUrl">
                <img :src="imageUrl" class="upload-image" />
                <div class="upload-handle" @click.stop>
                    <div class="handle-icon" @click="editImg" v-if="!self_disabled">
                        <el-icon><Edit /></el-icon>
                        <span>编辑</span>
                    </div>
                    <div class="handle-icon" @click="imgViewVisibleHandle">
                        <el-icon><ZoomIn /></el-icon>
                        <span>查看</span>
                    </div>
                    <div class="handle-icon" @click="deleteImg" v-if="!self_disabled">
                        <el-icon><Delete /></el-icon>
                        <span>删除</span>
                    </div>
                </div>
            </template>
            <template v-else>
                <div class="upload-empty">
                    <slot name="empty">
                        <el-icon><Plus /></el-icon>
                        <!-- <span>请上传图片</span> -->
                    </slot>
                </div>
            </template>
        </el-upload>
        <slot v-if="$slots.tip" name="tip"></slot>
        <div v-else class="el-upload__tip">
            {{ props.tip }}
        </div>
        <el-image-viewer v-if="imgViewVisible" @close="imgViewVisible = false" :url-list="[imageUrl]" />
    </div>
</template>

<script setup name="UploadImg">
import request from '@/request';
import { getUuid } from '@/commons/utils';
import { formContextKey, formItemContextKey, ElMessage } from 'element-plus';
import { ref, inject, computed, watch, nextTick } from 'vue';
const props = defineProps({
    imageUrl: { type: String, default: '', required: true }, // 图片地址 ==> 必传
    drag: { type: Boolean, default: true }, // 是否支持拖拽上传 ==> 非必传（默认为 true）
    disabled: { type: Boolean, default: false }, // 是否禁用上传组件 ==> 非必传（默认为 false）
    fileSize: { type: Number, default: 10 }, // 图片大小限制 ==> 非必传（默认为 10M）
    fileType: { type: Array, default: () => ['image/jpg', 'image/jpeg', 'image/png'] }, // 图片类型限制 ==> 非必传（默认为 ["image/jpeg", "image/png", "image/gif"]）
    tip: { type: String, default: '' },
    width: { type: String, default: '120px' }, // 组件宽度 ==> 非必传（默认为 150px）
    height: { type: String, default: '120px' }, // 组件高度 ==> 非必传（默认为 150px）
    borderRadius: { type: String, default: '4px' } // 组件边框圆角 ==> 非必传（默认为 8px）
});
const emit = defineEmits(['update:imageUrl', 'check-validate']);

// 生成组件唯一id
const uuid = ref('id-' + getUuid());
// 查看图片
const imgViewVisible = ref(false);
// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 判断是否禁用上传和删除
const self_disabled = computed(() => {
    return props.disabled || formContext?.disabled;
});
const handleHttpUpload = async options => {
    let formData = new FormData();
    formData.append('file', options.file);
    try {
        const { data } = await request('fileUploadServ', formData);
        emit('update:imageUrl', data.url);
        // 调用 el-form 内部的校验方法（可自动校验）
        formItemContext?.prop && formContext?.validateField([formItemContext.prop]);
        emit('check-validate');
    } catch (error) {
        options.onError(error);
    }
};

/**
 * @description 删除图片
 * */
const deleteImg = () => {
    emit('update:imageUrl', '');
};
/**
 * @description 编辑图片
 * */
const editImg = () => {
    const dom = document.querySelector(`#${uuid.value} .el-upload__input`);
    dom && dom.dispatchEvent(new MouseEvent('click'));
};

/**
 * @description 文件上传之前判断
 * @param rawFile 上传的文件
 * */
const beforeUpload = rawFile => {
    const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
    const imgType = props.fileType;
    if (!imgType.includes(rawFile.type)) {
        const typeMessage = `请上传${props.fileType.join('、').replace(/image\//g, '')}格式的图片`;
        ElMessage.error(typeMessage);
        return;
    }
    if (!imgSize) {
        const sizeMessage = `图片大小应小于${props.fileSize}M`;
        ElMessage.error(sizeMessage);
    }

    return imgType.includes(rawFile.type) && imgSize;
};

// 图片预览&点击遮罩关闭
const imgViewVisibleHandle = async () => {
    imgViewVisible.value = true;
    await nextTick();
    // 获取遮罩层dom
    let domImageMask = document.querySelector('.el-image-viewer__mask');
    if (!domImageMask) return;
    domImageMask.addEventListener('click', () => {
        // 点击遮罩层时调用关闭按钮的 click 事件
        document.querySelector('.el-image-viewer__close').click();
    });
};

// 图片上传成功提示
const uploadSuccess = () => {};

// 图片上传错误提示
const uploadError = () => {};
</script>
<style scoped lang="scss">
.is-error {
    .upload {
        :deep(.el-upload),
        :deep(.el-upload-dragger) {
            border: 1px dashed var(--el-color-danger) !important;
            &:hover {
                border-color: var(--el-color-primary) !important;
            }
        }
    }
}
:deep(.disabled) {
    .el-upload,
    .el-upload-dragger {
        cursor: not-allowed !important;
        background: var(--el-disabled-bg-color);
        border: 1px dashed var(--el-border-color-darker) !important;
        &:hover {
            border: 1px dashed var(--el-border-color-darker) !important;
        }
    }
}
.upload-box {
    .no-border {
        :deep(.el-upload) {
            border: none !important;
        }
    }
    :deep(.upload) {
        .el-upload {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            width: v-bind(width);
            height: v-bind(height);
            overflow: hidden;
            border: 1px dashed var(--el-border-color-darker);
            border-radius: v-bind(borderRadius);
            transition: var(--el-transition-duration-fast);
            &:hover {
                border-color: var(--el-color-primary);
                .upload-handle {
                    opacity: 1;
                }
            }
            .el-upload-dragger {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 100%;
                height: 100%;
                padding: 0;
                overflow: hidden;
                background-color: transparent;
                border: 1px dashed var(--el-border-color-darker);
                border-radius: v-bind(borderRadius);
                &:hover {
                    border: 1px dashed var(--el-color-primary);
                    .upload-empty .el-icon {
                        color: var(--el-color-primary);
                    }
                }
            }
            .el-upload-dragger.is-dragover {
                background-color: var(--el-color-primary-light-9);
                border: 2px dashed var(--el-color-primary) !important;
            }
            .upload-image {
                width: 100%;
                height: 100%;
                object-fit: contain;
            }
            .upload-empty {
                position: relative;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                line-height: 30px;
                color: var(--el-color-info);
                .el-icon {
                    font-size: 24px;
                    color: var(--el-text-color-secondary);
                }
            }
            .upload-handle {
                position: absolute;
                top: 0;
                right: 0;
                box-sizing: border-box;
                display: flex;
                align-items: center;
                justify-content: center;
                width: 100%;
                height: 100%;
                cursor: pointer;
                background: rgb(0 0 0 / 60%);
                opacity: 0;
                transition: var(--el-transition-duration-fast);
                .handle-icon {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    padding: 0 6%;
                    color: aliceblue;
                    .el-icon {
                        margin-bottom: 40%;
                        font-size: 130%;
                        line-height: 130%;
                    }
                    span {
                        font-size: 85%;
                        line-height: 85%;
                    }
                }
            }
        }
    }
    .el-upload__tip {
        margin-top: 8px;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
        line-height: 17px;
        text-align: center;
    }
}
</style>
